package com.ls.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ls.rbac.entity.Permission;
import com.ls.rbac.entity.RolePermission;
import com.ls.rbac.mapper.PermissionMapper;
import com.ls.rbac.mapper.RolePermissionMapper;
import com.ls.rbac.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liusheng
 * @since 2025--06--28
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private RolePermissionMapper rolePermissionMapper;
    //查询当前用户对应的所有权限
    @Override
    public List<Permission> selectPermissionListByUserId(Integer userId) {
        return permissionMapper.selectPermissionListByUserId(userId);
    }


    @Override
    public List<Integer> getPermissionIdsByRoleId(Integer roleId) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(queryWrapper);
        return rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toList());
    }

    public List<Permission> getPermissionTree() {
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Permission::getOrderNum);
        List<Permission> list = this.list(queryWrapper);
        Map<Integer, List<Permission>> perMap = list.stream().collect(Collectors.groupingBy(
                permission -> permission.getPid() == null ? 0 : permission.getPid()
        ));
        return buildDeptTree(perMap, 0);
    }

    @Override
    public List<Permission> getPermissionTreeParent(List<Permission> permissionList) {
        Map<Integer, List<Permission>> permissionMap = permissionList.stream()
                .collect(Collectors.groupingBy(permission ->
                        permission.getPid() == null ? 0 : permission.getPid()));
        return buildDeptTree(permissionMap, 0);
    }


    private List<Permission> buildDeptTree(Map<Integer, List<Permission>> perMap, Integer pid) {
        List<Permission> perTree = new ArrayList<>();
        List<Permission> perList = perMap.get(pid);
        if (perList != null) {
            for (Permission per : perList) {
                List<Permission> children = buildDeptTree(perMap, per.getId());
                per.setChildren(children);
                perTree.add(per);
            }
        }
        return perTree;
    }

    public List<Integer> getPermissionAndChildrenIds(Integer permissionId) {
        List<Integer> permissionIds = new ArrayList<>();
        permissionIds.add(permissionId);
        List<Permission> permissionList = this.list();
        if (permissionList == null || permissionList.isEmpty()) {
            return permissionIds;
        }
        collectChildPermissionIds(permissionList, permissionId, permissionIds);
        return permissionIds;
    }

    public void deletePermissionAndRolePermission(Integer permissionId) {
        // 删除角色权限关联
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getPermissionId, permissionId);
        rolePermissionMapper.delete(queryWrapper);
        // 删除权限
        this.removeById(permissionId);
    }


    private void collectChildPermissionIds(List<Permission> permissionList, Integer permissionId, List<Integer> permissionIds) {
        permissionList.stream()
                .filter(permission -> permissionId.equals(permission.getPid()))
                .forEach(permission -> {
                    permissionIds.add(permission.getId());
                    collectChildPermissionIds(permissionList, permission.getId(), permissionIds);
                });
    }
}
